<?php
/**
 * Dependency abstract analyzer
 *
 * PHP version 5
 *
 * @category  W
 * @package   Services
 * @author    Olivier Hoareau <olivier@phppro.fr>
 * @copyright 2009 PHPPRO http://www.phppro.fr
 * @license   http://dev.phppro.fr/license PHPPRO
 * @version   SVN: $Id:$
 * @link      http://dev.phppro.fr/projects/wdependency
 */
require_once 'W/Dependency/Analyzer/Interface.php';
/**
 * Dependency abstract analyzer
 *
 * @category  W
 * @package   Services
 * @author    Olivier Hoareau <olivier@phppro.fr>
 * @copyright 2009 PHPPRO http://www.phppro.fr
 * @license   http://dev.phppro.fr/license PHPPRO
 * @version   SVN: $Id$
 * @link      http://dev.phppro.fr/projects/wdependency
 */
abstract class W_Dependency_Analyzer_Abstract implements W_Dependency_Analyzer_Interface
{
    private $key;

    public function __construct()
    {
        $this->key = null;
    }
    public function configure($options=null)
    {
        if (false === isset($options['key'])) {
            return $this;
        }
        $this->setKey($options['key']);
        return $this;
    }
    public function getKey()
    {
        return $this->key;
    }
    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }
    public abstract function compute($data,$root);
    public function analyze($data)
    {
        $root = $data['root'];
        $data = $data['data'];
        $data = $this->compute($data,$root);
        $key = $this->getKey();
        if (null !== $key) {
            $data = array($key=>$data);
        }
        return $data;
    }
    public function updateDependencies(&$d,$item,$info,$prefix=null)
    {
        $item = $this->formatItemName($item,$prefix);

        if (false === isset($d[$item])) {
            $d[$item] = array();
        }

        foreach($info as $i=>$n) {
            if (false === isset($n['value'])) {
                continue;
            }
            $value = $this->formatItemName($n['value'],$prefix);
            if (false === isset($d[$item][$value])) {
                $d[$item][$value] = 0;
            }
            $d[$item][$value]++;
        }
        return $this;
    }
    public function formatItemName($item,$prefixes)
    {
        if (null !== $prefixes && true === is_array($prefixes)) {
            foreach($prefixes as $prefix) {
                if (null === $prefix) {
                    $prefix = '';
                }
                $prefix = str_replace(array(DIRECTORY_SEPARATOR),'/',$prefix);
                $item = str_replace(array(DIRECTORY_SEPARATOR),'/',$item);
                if ($prefix === substr($item,0,strlen($prefix))) {
                    $item = substr($item,strlen($prefix)+1);
                    break;
                }
            }
        }
        return $item;
    }
    public function __toString()
    {
        return get_class($this);
    }
}